package top.codetheory.thread;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CachedThreadPoolCase {

    @Resource
    ExecutorService executorService;

    static class Demo implements Runnable {
        List<Object> syncArrayList = Collections.synchronizedList(new ArrayList<>());

        @Override
        public void run() {
            try {
                // 模拟线程执行时间
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + " is running");
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        ExecutorService service = Executors.newCachedThreadPool();
//        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
//        Executors.newFixedThreadPool(2);
//        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
//        scheduledThreadPool.schedule(new Demo(), 5, TimeUnit.SECONDS);
//        for (int i = 0; i < 10; i++) {
//            service.submit(new Demo());
//            Thread.sleep(1);
//        }
//        service.shutdown();
        myThread();
    }

    public static void myThread() {
        AtomicInteger atomicInteger = new AtomicInteger(1);
        LinkedBlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                3,
                1000,
                TimeUnit.MILLISECONDS,
                linkedBlockingQueue,
                r -> new Thread(r, "myThread--" + atomicInteger.getAndIncrement()),
                new ThreadPoolExecutor.AbortPolicy()

        );

        threadPool.submit(new Thread(() -> {
                    System.out.println(Thread.currentThread().getName() + " is running");
                })
        );
        threadPool.shutdown();
    }
}
